package cn.tedu.dao;

import cn.tedu.entity.Product;
import cn.tedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ProductDao {


    public void insert(Product product) {
        //获取链接
        try(Connection conn= DBUtils.getConn()) {
            String sql = "insert into product values(null,?,?,?,?,0,0,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,product.getTitle());
            ps.setString(2,product.getAuthor());
            ps.setString(3,product.getIntro());
            ps.setString(4,product.getImgUrl());
            ps.setLong(5,product.getCreated());
            ps.setInt(6,product.getCategoryId());
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public List<Product> findAll() {
        List<Product> list = new ArrayList<>();
        //获取链接
        try(Connection conn= DBUtils.getConn()) {
            String sql = "select * from product";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                int id = rs.getInt(1);
                String title = rs.getString(2);
                String author = rs.getString(3);
                String intro = rs.getString(4);
                String imgUrl =rs.getString(5);
                int viewCount = rs.getInt(6);
                int likeCount =rs.getInt(7);
                long created = rs.getLong(8);
                int categoryId = rs.getInt(9);
                list.add(new Product(id,title,author,intro,imgUrl,viewCount,likeCount,
                        created, categoryId));

            }



        } catch (Exception e) {
            e.printStackTrace();
        }


        return list;

    }
}
